package org.changs.nav.ui.nav;

import android.animation.Animator;
import android.app.Dialog;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.text.Editable;
import android.view.View;
import android.view.ViewGroup;

import org.changs.aplug.base.BaseDialog;
import org.changs.aplug.interf.Action1;
import org.changs.aplug.simple.SimpleTextWatcher;
import org.changs.aplug.utils.EmptyUtils;
import org.changs.aplug.utils.KeyboardUtils;
import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.nav.R;
import org.changs.nav.databinding.CarNumberItemBinding;
import org.changs.nav.databinding.CarNumberLayoutBinding;

import java.util.Arrays;

/**
 * Created by yincs on 2017/9/7.
 */

public class CarNumberEditDialog extends BaseDialog {
    private static final String TAG_CAR_NUMBER = "TAG_CAR_NUMBER";
    private Action1<String> mDoneAction;

    public static CarNumberEditDialog newInstance(String carNumber, Action1<String> doneAction) {
        Bundle args = new Bundle();
        args.putString(TAG_CAR_NUMBER, carNumber);
        CarNumberEditDialog fragment = new CarNumberEditDialog();
        fragment.setArguments(args);
        fragment.mDoneAction = doneAction;
        return fragment;
    }

    private static final String[] PROVINCE_NICKNAME = {
            "京", "津", "冀", "晋", "蒙", "辽", "吉", "黑",
            "沪", "苏", "浙", "皖", "闽", "赣", "鲁", "豫",
            "鄂", "湘", "粤", "桂", "琼", "渝", "川", "贵",
            "云", "藏", "陕", "甘", "青", "宁", "新"
    };

    private CarNumberLayoutBinding mBinding;
    private SimpleAdapter<String, CarNumberItemBinding> mAdapter;
    private boolean mAnimRunning;

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Dialog dialog = new Dialog(getContext());
        mBinding = DataBindingUtil.inflate(getContext().getLayoutInflater(), R.layout.car_number_layout, null, false);
        dialog.setContentView(mBinding.getRoot());
        if (dialog.getWindow() != null) {
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        }
        dialog.setCanceledOnTouchOutside(false);
        initUI();
        initData();
        return dialog;
    }


    private void initData() {
        if (!getContext().isFinishing() && mDoneAction == null) {
            dismiss();
            return;
        }
        String carNumber = getArguments().getString(TAG_CAR_NUMBER, "");
        if (EmptyUtils.isEmpty(carNumber) || carNumber.length() < 2) return;
        String province = carNumber.substring(0, 1);
        String number = carNumber.substring(1, carNumber.length());
        for (int i = 0; i < PROVINCE_NICKNAME.length; i++) {
            String letter = PROVINCE_NICKNAME[i];
            if (letter.equals(province)) {
                mAdapter.setSelectIndex(i);
                break;
            }
        }
        mBinding.tvProvince.setText(province);
        mBinding.etCarNumber.setText(number);
        mBinding.etCarNumber.setSelection(number.length());
    }

    private void initUI() {
        mAdapter = new SimpleAdapter<String, CarNumberItemBinding>(R.layout.car_number_item) {
            @Override
            public void onBindViewHolder(CarNumberItemBinding binding, int position) {
                final int index = position;
                final String name = getData().get(position);
                binding.tvName.setText(name);
                binding.getRoot().setOnClickListener(v -> {
                    mAdapter.setSelectIndex(index);
                    mAdapter.notifyDataSetChanged();
                    mBinding.tvProvince.setText(name);
                });
            }
        };
        mBinding.rccView.setLayoutManager(new GridLayoutManager(getContext(), 8));
        mBinding.rccView.setAdapter(mAdapter);
        mAdapter.getData().addAll(Arrays.asList(PROVINCE_NICKNAME));
        mAdapter.setSelectIndex(0);
        mAdapter.notifyDataSetChanged();
        mBinding.rccView.setVisibility(View.GONE);
        mBinding.rccView.setTranslationY(2000);
        mBinding.tvProvince.setOnClickListener(v -> {
            if (mAnimRunning) return;
            if (mBinding.rccView.getVisibility() == View.GONE) {
                mBinding.rccView.animate()
                        .translationY(0)
                        .setDuration(500)
                        .setListener(new MyAnimatorListener(false))
                        .start();
            } else {
                mBinding.rccView.animate()
                        .translationY(2000)
                        .setDuration(500)
                        .setListener(new MyAnimatorListener(true))
                        .start();
            }
        });
        mBinding.btnDone.setOnClickListener(v -> {
            final String province = mBinding.tvProvince.getText().toString();
            final String carNumber = mBinding.etCarNumber.getText().toString();
            String result;
            if (carNumber.length() < 6) {
                result = "";
            } else {
                result = province + carNumber;
            }
            if (mDoneAction != null) mDoneAction.call(result);
            dismiss();
        });
        mBinding.etCarNumber.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                mBinding.btnDone.setEnabled(s.length() == 6);
                mBinding.btnClear.setVisibility(s.length() > 0 ? View.VISIBLE : View.GONE);
            }
        });
        mBinding.btnClear.setOnClickListener(v -> mBinding.etCarNumber.setText(""));
    }

    private class MyAnimatorListener implements Animator.AnimatorListener {

        private boolean endGone;

        public MyAnimatorListener(boolean endGone) {
            this.endGone = endGone;
        }

        @Override
        public void onAnimationStart(Animator animation) {
            mAnimRunning = true;
            mBinding.rccView.setVisibility(View.VISIBLE);
            mBinding.getRoot().requestFocus();
            KeyboardUtils.hideSoftInput(mBinding.etCarNumber);
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            mAnimRunning = false;
            if (endGone) {
                mBinding.rccView.setVisibility(View.GONE);
                KeyboardUtils.showSoftInput(getContext(), mBinding.etCarNumber);
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            mAnimRunning = false;
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
            mAnimRunning = true;
        }
    }

}
